<template>
  <div class="app-container" style="height: 100%">
    <el-form ref="queryForm" :model="queryParams" size="mini" inline style="white-space: nowrap; overflow-x: auto" :class="{ disabled: disableAction }">
      <el-form-item>
        <header-select @selectProject="onSelectProject" style="line-height: normal" />
      </el-form-item>
      <el-form-item prop="taskType">
        <el-select v-model="queryParams.taskType" placeholder="请选择任务来源" clearable style="width: 140px">
          <el-option v-for="item in taskSourceList" :key="item.value" :label="item.label" :value="item.value" />
        </el-select>
      </el-form-item>
      <el-form-item prop="taskName">
        <el-input v-model.trim="queryParams.taskName" placeholder="请输入任务名称" clearable @keyup.enter.native="handleQuery" style="width: 140px" />
      </el-form-item>
      <el-form-item>
        <el-button size="mini" type="primary" icon="el-icon-search" @click="handleQuery">搜索</el-button>
        <el-button size="mini" icon="el-icon-refresh" @click="resetQuery">重置</el-button>
        <!--
        <template v-if="showBtns.add">
          <el-button size="mini" type="primary" icon="el-icon-plus" @click="openAddItem" v-if="queryParams.projectId">临时任务</el-button>
          <el-popover placement="top" trigger="hover" content="请点击选择左侧项目" v-else>
            <el-button slot="reference" size="mini" icon="el-icon-plus" style="margin-left: 10px">临时任务</el-button>
          </el-popover>
        </template>
        -->
      </el-form-item>
    </el-form>

    <el-table v-loading="listLoading" :data="list" size="small" height="calc(100% - 100px)">
      <el-table-column label="任务名称" show-overflow-tooltip min-width="200">
        <span slot-scope="{ row }">
          <el-tag type="info" class="source-tag" size="mini" v-if="row.taskType" :style="{ color: displaySource('color', row.taskType) }" :title="displaySource('label', row.taskType)">
            {{ displaySource('abbr', row.taskType) }}
          </el-tag>
          {{ row.taskName }}
        </span>
      </el-table-column>
      <el-table-column label="巡更类型" prop="patrolTypeName" show-overflow-tooltip min-width="200" />
      <el-table-column label="任务开始时间" prop="taskBeginDate" width="150" />
      <el-table-column label="任务结束时间" prop="taskEndDate" width="150" />
      <el-table-column label="巡更点位" min-width="100">
        <el-popover slot-scope="{ row }" placement="right" width="400" trigger="click">
          <span class="pointer" slot="reference">
            共
            <el-link type="primary" style="line-height: 1">{{ row.spotNum }}</el-link>
            个点位
          </span>
          <el-table :data="row.cqPatrolTaskSpotList || []" size="mini">
            <el-table-column label="点位编码" prop="spotCode" show-overflow-tooltip min-width="100" />
            <el-table-column label="点位名称" prop="spotName" show-overflow-tooltip min-width="100" />
            <el-table-column label="负责人" prop="principalNames" show-overflow-tooltip min-width="100" />
          </el-table>
        </el-popover>
      </el-table-column>
      <el-table-column label="涉及负责人" prop="principalNames" show-overflow-tooltip min-width="100" />
      <el-table-column label="活动状态" align="center" min-width="80">
        <dict-tag slot-scope="{ row }" :options="dict.type.cq_patrol_task_status" :value="row.status" />
      </el-table-column>
      <el-table-column label="操作" width="180">
        <template slot-scope="{ row }">
          <el-button size="mini" type="text" icon="el-icon-edit" @click="$refs.EditItem.open(row)" v-if="row.isEditable">修改</el-button>
          <el-button size="mini" type="text" icon="el-icon-tickets" @click="$refs.TaskInfo.open(row)" v-if="showBtns.info">详情</el-button>
          <el-button size="mini" type="text" icon="el-icon-circle-close" :loading="row.cancelTaskLoading" @click="cancelTask(row)" v-if="row.isCancellable">取消</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize" @pagination="getList" />

    <EditItem ref="EditItem" v-model="showEditItem" @ok="getList" />
    <TaskInfo ref="TaskInfo" />
  </div>
</template>
<script>
// 巡更任务列表
import auth from '@/plugins/auth'
import { getTask, setTaskStatus } from '@/api/cq/patrol'
import HeaderSelect from './components/HeaderSelect'
import { CUSTOM_TASK, taskSourceList } from './utils/common'
import EditItem from './components/EditTask'
import TaskInfo from './components/TaskInfo'

const taskSource2obj = taskSourceList.reduce((o, i) => !void (o[i.value] = i) && o, {})
const displaySource = (key, value) => (taskSource2obj[value] || {})[key]

export default {
  name: 'PatTaskList',
  components: { HeaderSelect, EditItem, TaskInfo },
  dicts: ['cq_patrol_task_status'],
  data() {
    return {
      displaySource,
      // 下拉不含自定任务
      taskSourceList: taskSourceList.filter(i => i.value !== CUSTOM_TASK),
      listLoading: false,
      total: 0,
      list: [],
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        projectId: '',
        taskType: '',
        taskName: ''
      },
      showEditItem: false
    }
  },
  computed: {
    disableAction() {
      return this.listLoading
    },
    showBtns() {
      // 操作按钮权限
      const permCode = 'cq:patrol:task'
      const edit = auth.hasPermi(`${permCode}:edit`)
      const add = auth.hasPermi(`${permCode}:add`)
      const remove = auth.hasPermi(`${permCode}:remove`)
      const info = auth.hasPermi(`${permCode}:info`)
      const taskCancel = auth.hasPermi(`${permCode}:taskCancel`)
      return { edit, add, remove, info, taskCancel }
    }
  },
  methods: {
    onSelectProject(project) {
      const projectId = project?.id || ''
      this.queryParams.projectId = projectId
      if (projectId) this.getList()
    },
    async getList() {
      const { showBtns } = this
      const { projectId } = this.queryParams
      if (!projectId) {
        this.$message('请选择项目')
        return (this.list = [])
      }

      this.listLoading = true
      const res = await getTask(this.queryParams).catch(() => false)
      this.listLoading = false
      if (res === false) return

      const data = res.rows || []
      data.map(i => {
        i.isEditable = showBtns.edit && i.taskType === '3' && i.status === 0
        i.isCancellable = showBtns.taskCancel && [0, 1].includes(i.status)
        i.cancelTaskLoading = false
        i.spotNum = i.cqPatrolTaskSpotList?.length || ''
      })
      this.list = data
      this.total = res.total || 0
    },
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    resetQuery() {
      this.resetForm('queryForm')
      this.handleQuery()
    },
    openAddItem() {
      this.$refs.EditItem.open({ projectId: this.queryParams.projectId })
    },
    async cancelTask(item) {
      const res1 = await this.$prompt('', '取消任务', {
        inputPlaceholder: '请填写取消原因',
        inputValidator: val => !!(val || '').trim(),
        inputErrorMessage: '请填写取消原因'
      }).catch(action => ({ action }))
      if (res1.action !== 'confirm') return

      const reason = (res1.value || '').trim()
      const opt = { patTaskId: item.patTaskId, status: -1, reason }
      item.cancelTaskLoading = true
      const res = await setTaskStatus(opt).catch(() => false)
      item.cancelTaskLoading = false
      if (res === false) return

      this.$message.success('已取消任务')
      this.getList()
    }
  }
}
</script>
<style lang="scss" scoped>
.source-tag {
  zoom: 0.9;
  margin-right: 2px;
  padding: 0 4px;
}
</style>
